package com.ljw.hmall.item.service.impl;

import com.alibaba.spring.util.BeanUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljw.hmall.dto.PageDTO;
import com.ljw.hmall.item.mapper.ItemMapper;
import com.ljw.hmall.item.pojo.Item;
import com.ljw.hmall.item.service.IItemService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    ItemMapper itemMapper;

    @Override
    public PageDTO<Item> selectPages(Integer page, Integer size) {

        Page<Item> itemPage = new Page<>(page, size);

        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("update_time");
        Page<Item> pages = itemMapper.selectPage(itemPage,queryWrapper);
        PageDTO<Item> pageDTO = new PageDTO<>(pages.getTotal(), pages.getRecords());
        return pageDTO;
    }

    @Override
    public Item selectOne(Long id) {

        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Item::getId, id);
        Item item = itemMapper.selectOne(queryWrapper);
        return item;
    }

    @Override
    public void insertOne(Item item) {
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemMapper.insert(item);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Item::getId,id);
        itemMapper.update(item,queryWrapper);
    }

    @Override
    public void updateStock(Long itemId,Integer num) {
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Item::getId,itemId);
        Item item = itemMapper.selectOne(queryWrapper);
        Integer stock = item.getStock();
        stock=stock-num;
        item.setStock(stock);
        itemMapper.update(item,queryWrapper);
    }

    @Override
    public void addStock(Long itemId, Integer num) {
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Item::getId,itemId);
        Item item = itemMapper.selectOne(queryWrapper);
        Integer stock = item.getStock();
        stock=stock+num;
        item.setStock(stock);
        itemMapper.updateById(item);
    }
}
